package Demo17;

class Solution {
    public int search(int[] nums, int target) {
        int left = 0,right = nums.length - 1;
        while(left <= right) {
            int mid = left + (right - left) / 2; // 这里不直接使用 (right + left) / 2 是为了防止溢出的情况
                                                 // 我们这里这么写 右下标没有溢出, 那左下标加上又下标的一半,也一定不会溢出
            if(nums[mid] > target) {
                right = mid - 1;
            }else if(nums[mid] < target) {
                left = mid + 1;
            }else {
                return mid;
            }
        }
        return -1;
    }
}
class Demo {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int ret = solution.search(new int[] {-1,0,3,5,9,12},9);
        System.out.println(ret);
    }
}